<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of BMemberPointCooker
 *
 * @author i062261
 */
class BAMemberPointCooker extends BAEventCooker {

    const Action_AddPoint = 'addPoint';
    const Action_DeductPoint = 'deductPoint';
    const Action_AddPoint_With_Bill = 'addPointWithBill';
    const Permit_Allow = 'allow';
    const Permit_Deny = 'deny';

    /**
     * this function will check permit first, if not find permit result, will
     * send request to handle
     * @param type $operation
     * @param type $event
     * @param type $user
     */
    public function checkActionPermit($memberPointType, $action, $permit) {

        if (is_string($memberPointType))
            $memberPointTypeName = $memberPointType;

        if ($memberPointType instanceof BACategory) {
            $memberPointTypeName = $memberPointType->getName();
        }

        $permitTable = new BASpaceSheet('memberPointPermit');

        $context = array();
        $context['spaceId'] = Blyn::app()->getActiveSpace()->getId();
        $context['memberPointType'] = $memberPointTypeName;
        $context['action'] = $action;
        $context['permit'] = $permit;
        $context['sender_operationId'] = Blyn::app()->getActiveOperation()->getId();
        $eventCooker = new BAEventCooker();
        $event = $eventCooker->getCurrentEvent();
        if ($event != NULL) {
            $eventType = $eventCooker->getEventTypeByEvent($event);
            $context['sender_eventTypeId'] = $eventType->getId();
        }

        $list = $permitTable->getList(array('itemData' => $context));

        if ($list != NULL) {
            return TRUE;
            /*
              $permitResult = $list->getItem('permitResult')->getValue();
              if ($permitResult == TRUE || strtolower($permitResult) == 'true')
              return TRUE;
              else {
              return FALSE;
              }
             * 
             */
        }

        //if not find permit in permit table, send as request into request table
        $permitRequestTable = new BASpaceSheet('memberPointPermitRequest');
        $rList = $permitRequestTable->getList(array('itemData' => $context));
        if ($rList == NULL) {
            $rList = $permitRequestTable->addList($context);
        }
        return $rList;
    }

    /**
     * this function usually is called on App as initial data
     * @param type $memberPointTypeName
     * @param type $action
     * @param type $permit
     * @param type $sender, usually is array contain sender operationId and sender eventTypeId
     * @return type
     */
    public function addActionPermit($memberPointType, $action, $permit = 'allow', $eventType = NULL, $operation = NULL) {
        $eventCooker = new BAEventCooker();
        $currentEvent = $eventCooker->getCurrentEvent();
        $permitTable = new BASpaceSheet('memberPointPermit', $currentEvent);

        $oMemberPointType = $this->getMemberPointType($memberPointType);

        $context = array();
        $context['spaceId'] = Blyn::app()->getActiveSpace()->getId();
        $context['memberPointTypeName'] = $oMemberPointType->getName();
        $context['memberPointTypeId'] = $oMemberPointType->getId();
        $context['action'] = $action;
        $context['permit'] = $permit;

        $eventCooker = new BAEventCooker();
        if (!$eventType instanceof BACategory) {
            $eventType = $eventCooker->getCurrentEventType();
        }

        if ($eventType instanceof BACategory) {
            $context['eventTypeId'] = $eventType->getId();
            $context['eventTypeAlias'] = $eventCooker->getEventTypeAlias($eventType);
        }

        if ($operation == NULL) {
            $operation = Blyn::app()->getActiveOperation();
        }

        if ($operation instanceof BOperation) {
            $context['operationId'] = $operation->getId();
            $context['operationName'] = $operation->getName();
        }

        $list = $permitTable->getList(array('itemData' => $context));
        if ($list == NULL) {
            $list = $permitTable->addList($context);
        }
        return $list;
    }

    /**
     * 
     * @param type $name, name format appName_memberPointName
     * @param type $data
     */
    public function addMemberPointType($name, $alias = null, $data = NULL) {

        $memberPointTypeRoot = $this->getMemberPointTypeRoot();

        if ($alias == NULL) {
            $alias = $name;
        }

        $type = $memberPointTypeRoot->addChild(array('name' => $name, 'value' => $alias));

        if ($type != NULL) {
            $itemData = array();
            //check if exist type
            $itemData['memberPointTypeId'] = $type->getId();
            //$itemData['eventId']= $this->getCurrentEvent()->getId();
            $typeTable = new BAAttributeSheet($type);
            $list = $typeTable->getList(array('itemData' => $itemData));

            if ($list == NULL) {
                $list = $typeTable->getNewList();
            }

            $itemData['name'] = $name;
            $itemData['alias'] = $alias;
            if (is_array($data)) {
                $itemData+=$data;
            }

            //check if data changed, if not, no need to save
            $list2 = $typeTable->getList(array('itemData' => $itemData));
            if ($list2 == NULL)
                $list->addItems($itemData);

            //add permit for type
            $this->addMemberPointTypePermit($type->getId());

            //add permit for addPoint and deductPoint
            //$eventCooker = new BAEventCooker();
            //$eventType = $eventCooker->getCurrentEventType();
            $this->addActionPermit($type, self::Action_AddPoint_With_Bill);
            $this->addActionPermit($type, self::Action_DeductPoint);

            return $type;
        }

        return FALSE;
    }

    /**
     * 激活操作将加ALLOW PERMIT
     * @param type $nameOrId
     * @param type $permit
     * @param type $data
     * @return boolean
     */
    public function addMemberPointTypePermit($nameOrId, $permit = 'allow', $data = NULL) {

        $eventCooker = new BAEventCooker();
        $currentEvent = $eventCooker->getCurrentEvent();
        $mptPermitTable = new BASpaceSheet('memberPointTypePermit', $currentEvent);

        $memberPointTypeId = NULL;
        if (is_string($nameOrId) && !is_numeric($nameOrId)) {
            $memberPointTypeName = $nameOrId;
            $memberPointType = $this->getMemberPointType($nameOrId);
            if ($memberPointType != NULL) {
                $memberPointTypeId = $memberPointType->getId();
            }
        }
        if (is_numeric($nameOrId)) {
            $memberPointTypeId = $nameOrId;
            $memberPointType = new BACategory($memberPointTypeId);
            $memberPointTypeName = $memberPointType->getName();
        }

        if ($nameOrId instanceof BACategory) {
            $memberPointType = $nameOrId;
            $memberPointTypeId = $memberPointType->getId();
            $memberPointTypeName = $memberPointType->getName();
        }

        if ($memberPointTypeId != NULL) {
            $itemData = array();
            $itemData['memberPointTypeId'] = $memberPointTypeId;
            $itemData['memberPointTypeName'] = $memberPointTypeName;
            $itemData['permit'] = $permit;
            $itemData['spaceId'] = Blyn::app()->getActiveSpace()->getId();
            $list = $mptPermitTable->getList(array('itemData' => $itemData));
            if ($list == NULL) {
                $list = $mptPermitTable->addList($itemData);
            }
            return $list;
        }

        return FALSE;
    }

    public function getMemberPointTypePermit($nameOrId, $spaceId = NULL, $data = NULL) {

        $itemContext = array();
        if ($spaceId == NULL) {
            $spaceId = Blyn::app()->getActiveSpace()->getId();
            $itemContext['spaceId'] = $spaceId;
        }
        if (is_numeric($nameOrId) && $nameOrId > 0) {
            $itemContext['memberPointTypeId'] = $nameOrId;
        }
        if (is_string($nameOrId) && !is_numeric($nameOrId) && $nameOrId != NULL) {
            $itemContext['memberPointTypeName'] = $nameOrId;
        }

        $eventCooker = new BAEventCooker();
        $currentEvent = $eventCooker->getCurrentEvent();
        $mptTable = new BASpaceSheet('memberPointTypePermit', $currentEvent);

        $list = $mptTable->getList(array('itemData' => $itemContext));
        if ($list != NULL) {
            return $list->getItem('permit')->getValue();
        }
        return FALSE;
    }

    public function getMemberPointAccountHistory($memberPointType = null, $accountId = NULL, $limit = 20, $orderBy = 'actionTime Desc') {

        if ($memberPointType == NULL)
            $memberPointType = $this->getMemberCurrentPointType();

        $oMemberPointAccount = $this->getMemberPointAccount($accountId, $memberPointType);
        if ($oMemberPointAccount != NULL) {
            $memberPointTable = new BASpaceSheet('memberPointHistory', $oMemberPointAccount);
        }
//        $memberPointTable = new BASpaceSheet('memberPointHistory', $memberPointType);
        $view = array();
        if ($accountId != NULL && $accountId > 0) {
            if ($memberPointType instanceof BACategory) {
                $itemData = array();
//            $itemData['memberPointTypeId'] = $memberPointType->getId();
                $itemData['accountId'] = $accountId;

                $view = $memberPointTable->getView(array('itemData' => $itemData, 'limit' => $limit, 'orderBy' => $orderBy));
//            foreach ($view as $id => $list) {
//                $mpaList[$id]['mobile'] = $list->getItem('mobile')->getValue();
//                $mpaList[$id]['email'] = $list->getItem('email')->getValue();
//                $mpaList[$id]['userName'] = $list->getItem('userName')->getValue();
//                $mpaList[$id]['gender'] = $list->getItem('gender')->getValue();
//                $mpaList[$id]['accountId'] = $list->getItem('accountId')->getValue();
//                $mpaList[$id]['lastChangeTime'] = $list->getItem('lastChangeTime')->getValue();
//            }
            }
        }
        return $view;
    }

    public function getMemberPointAccountList($memberPointType = null, $data = NULL) {

        $memberPointType = $this->getMemberPointType($memberPointType);

        $memberPointAccountTable = new BASpaceSheet('memberPointAccount', $memberPointType);
        $view = array();
        if ($memberPointType instanceof BACategory) {
            $itemData = array();
            $itemData['memberPointTypeId'] = $memberPointType->getId();

            $view = $memberPointAccountTable->getView(array('itemData' => $itemData));
//            foreach ($view as $id => $list) {
//                $mpaList[$id]['mobile'] = $list->getItem('mobile')->getValue();
//                $mpaList[$id]['email'] = $list->getItem('email')->getValue();
//                $mpaList[$id]['userName'] = $list->getItem('userName')->getValue();
//                $mpaList[$id]['gender'] = $list->getItem('gender')->getValue();
//                $mpaList[$id]['accountId'] = $list->getItem('accountId')->getValue();
//                $mpaList[$id]['lastChangeTime'] = $list->getItem('lastChangeTime')->getValue();
//            }
        }
        return $view;
    }

    /**
     * this function use to find memberPointAccount by context,for example,
     * to get memberPointAccount
     * @param type $itemContext,mix
     */
    public function getMemberPointAccount($itemContext = NULL, $memberPointType = NULL) {

        if ($memberPointType == NULL) {
            $memberPointType = $this->getCurrentMemberPointType();
        } else {
            $memberPointType = $this->getMemberPointType($memberPointType);
        }

        $memberPointAccountTable = new BASpaceSheet('memberPointAccount', $memberPointType);

        $itemData = array();
        if (is_numeric($itemContext) && $itemContext > 0) {
            return $memberPointAccountTable->getListById($itemContext);
        }

        if ($itemContext instanceof BTreeList) {
            return $itemContext;
        }

        //$itemData = $itemContext;
        $userCooker = new BAUserCooker();
        $oUserInfo = $userCooker->getUserInfo($itemContext);
        if ($oUserInfo != NULL) {
            $itemData['userInfoId'] = $oUserInfo->getId();
            //$itemData['memberPointTypeId'] = $memberPointType->getId();
            if (isset($itemContext['mobile'])) {
                unset($itemContext['mobile']);
            }
            if (isset($itemContext['email'])) {
                unset($itemContext['email']);
            }
            return $memberPointAccountTable->getList(array('itemData' => $itemData));
        }
        return $memberPointAccountTable->getList(array('itemData' => $itemContext));
    }

    /**
     * this function use to get memberPointAccount by user, if no memberPointType data provide
     * return first memberPointType
     * @param type $user
     * @return boolean
     */
    public function getMemberPointAccountByUser($memberPointType = NULL, $user = NULL) {
        if ($user == NULL)
            $user = Blyn::app()->getCurrentUser();

        $userCooker = new BAUserCooker();
        $oUserInfo = $userCooker->getUserInfo();

        if ($oUserInfo != NULL) {

            $memberPointType = $this->getMemberPointType($memberPointType);

            if ($memberPointType != NULL) {
                $memberPointAccountTable = new BASpaceSheet('memberPointAccount', $memberPointType);
                $itemData['userInfoId'] = $oUserInfo->getId();
                return $memberPointAccountTable->getList(array('itemData' => $itemData));
            }
        }

        return FALSE;
    }

    public function getMemberPointAccountListByUser($user = NULL) {
        if ($user == NULL)
            $user = Blyn::app()->getCurrentUser();

        $mobileAttr = $user->getAttribute('userInfo.mobile');
        if ($mobileAttr != NULL) {
            $mobile = $mobileAttr->getValue();
        }

        $memberPointTypeList = $this->getMemberPointTypeList('objectList');

        $accountList = array();
        foreach ($memberPointTypeList as $memberPointType) {
            if ($memberPointType != NULL) {
                $memberPointAccountTable = new BASpaceSheet('memberPointAccount', $memberPointType);
                if (isset($mobile) && $mobile != NULL) {
                    $itemData['mobile'] = $mobile;
                    $account = $memberPointAccountTable->getList(array('itemData' => $itemData));
                    $accountList[$account->getId()] = $account;
                }
            }
        }

        return $accountList;
    }

    public function getCurrentMemberPointAccountList($billType = NULL, $pointData = NULL, $userData = NULL, $limit = 20) {

        $user = Blyn::app()->getCurrentUser();
        $userData = array();
        $userData['userId'] = $user->getId();

        $userCooker = new BAUserCooker();
        $userInfo = $userCooker->getUserInfo($userData);

        if (!is_array($pointData)) {
            $pointData = array();
        }

//        $userBillList = array();
//
        if ($userInfo != NULL) {
            if ($userInfo->getItem('mobile') != NULL) {
                $mobile = $userInfo->getItem('mobile')->getValue();
                $userInfoId = $userInfo->getId();
//                if ($mobile != NULL) {
//                    $pointData['mobile'] = $mobile;
//                    $userBillList = $this->getBillList($billType, $pointData, $limit);
//                }
            }
        }

        $memberPointTypeList = $this->getMemberPointTypeList('objectList');

        $accountList = array();
        foreach ($memberPointTypeList as $memberPointType) {
            if ($memberPointType != NULL) {
                $memberPointAccountTable = new BASpaceSheet('memberPointAccount', $memberPointType);
                if (isset($userInfoId) && $userInfoId != NULL) {
                    $itemData['userInfoId'] = $userInfoId;
                    $account = $memberPointAccountTable->getList(array('itemData' => $itemData));
                    if ($account) {
                        $accountList[$account->getId()] = $account;
                    }
                }
            }
        }

        return $accountList;
    }

    public function removeMemberPointType($name, $data = NULL) {
        $memberPointTypeRoot = $this->getMemberPointTypeRoot();

        return $memberPointTypeRoot->removeChild($name);
    }

    public function getMemberPointType($nameOrId = null, $data = NULL) {

        if (is_numeric($nameOrId) && $nameOrId > 0) {
            return new BACategory($nameOrId);
        }

        if (is_string($nameOrId) && $nameOrId != NULL && $nameOrId != '') {
            $memberPointTypeRoot = $this->getMemberPointTypeRoot();
            return $memberPointTypeRoot->getChild($nameOrId);
        }

        if ($nameOrId instanceof BACategory)
            return $nameOrId;

        //if not find any type, return first type defined
        $memberPointTypeRoot = $this->getMemberPointTypeRoot();
        $children = $memberPointTypeRoot->getChildrenAsLeaf();
        if ($children != NULL)
            return reset($children);

        return FALSE;
    }

    public function checkAllowUserInfoForMemberPointAccount($memberPointType, $userInfo) {

        $memberPointType = $this->getMemberPointType($memberPointType);

        $memberPointAccountTable = new BASpaceSheet('memberPointAccount', $memberPointType);

        $itemData = $this->populateUserInfo($userInfo);
        if (empty($itemData))
            return FALSE;

        $userCooker = new BAUserCooker();
        $oUserInfo = $userCooker->getUserInfo($itemData);

        if ($oUserInfo != NULL) {
            $userData = $oUserInfo->getItemsInArray();
            $itemContext = array();
            $itemContext['userInfoId'] = $oUserInfo->getId();
            $itemContext['memberPointTypeId'] = $memberPointType->getId();
            $account = $memberPointAccountTable->getList(array('itemData' => $itemContext));
            if ($account != NULL) {
                $error = new BAError();
                if (is_array($userInfo)) {
                    if (isset($userInfo['mobile']) && isset($userData['mobile']) && $userData['mobile'] == $userInfo['mobile']) {
                        $error->addError('手机号已经被使用！', 'wrongMobile');
                    }
                    if (isset($userInfo['email']) && isset($userData['email']) && $userData['email'] == $userInfo['email']) {
                        $error->addError('EMAIL已经被使用！', 'wrongEmail');
                    }
                }
                if ($error->haveErrors()) {
                    return $error;
                }
            }
        }

        return TRUE;
    }

    public function addMemberPointAccount($memberPointType, $userInfo, $accountInfo = null, $memberPointAccount = NULL) {

        $userData = $this->populateUserInfo($userInfo);

        if (empty($userData))
            return FALSE;

        //如果用户信息不存在，就添加用户信息
        $userCooker = new BAUserCooker();
        $oUserInfo = $userCooker->addUserInfo($userData);
        /*
          $oUserInfo = $userCooker->getUserInfo($userData);
          if ($oUserInfo == NULL) {
          $oUserInfo = $userCooker->addUserInfo($userData);
          if ($oUserInfo instanceof BAError || $oUserInfo == NULL) {
          return FALSE;
          }
          } else {
          $userCooker->addUserInfo($userData);
          }
         * 
         */

        $memberPointType = $this->getMemberPointType($memberPointType);

        if ($memberPointAccount == NULL) {

            $memberPointAccountTable = new BASpaceSheet('memberPointAccount', $memberPointType);

            //check whether an exist account by user info
            $itemContext = array();
            $memberPointAccount = $this->getMemberPointAccount(array('userInfoId' => $oUserInfo->getId()), $memberPointType);

            if ($memberPointAccount == NULL) {
                $memberPointAccount = $memberPointAccountTable->getNewList();
            }
        }

        //init account
        if ($memberPointAccount->getItem('accountId') == NULL) {
            //first time add account, set memberPoint as 0
            $itemData['memberPoint'] = 0;
            $itemData['memberPointTypeId'] = $memberPointType->getId();
            $itemData['memberPointTypeName'] = $memberPointType->getName();
            $itemData['memberPointTypeAlias'] = $memberPointType->getValue();
            $itemData['accountId'] = $memberPointAccount->getId();
            $itemData['userInfoId'] = $oUserInfo->getId();
        }

        $itemData['lastChangeTime'] = time();
        if (is_array($accountInfo) && $accountInfo != NULL) {
            $itemData += $accountInfo;
        }

        if ($memberPointAccount instanceof BTreeList) {
            if ($memberPointAccount->getName() != 'list' . $memberPointAccount->getId()) {
                $memberPointAccount->name = 'list' . $memberPointAccount->getId();
                $memberPointAccount->setOwner($memberPointType);
                $memberPointAccount->save();
            }
            $memberPointAccount->addItems($itemData);
            //$itemData['memberPointAccountId'] = $memberPointAccount->getId();
            //add memberCard for memberPointAccount
            //$memberCardCooker = new BAMemberCardCooker();
            //$memberCardCooker->addCard(BAMemberCardCooker::CardType_MemberPoint_Card, $itemData);

            return $memberPointAccount;
        }

        return FALSE;
    }

    protected function populateUserInfo($userInfo) {
        $userTel = NULL;
        $userEmail = NULL;
        $itemData = array();
        if (is_numeric($userInfo) && $userInfo != NULL) {
            $mobile = $mobile;
            $itemData['mobile'] = $mobile;
        }
        if (is_string($userInfo)) {
            if (strpos($userInfo, '@')) {
                $userEmail = $userInfo;
                $itemData['email'] = $userEmail;
            }
        }
        if (is_array($userInfo)) {
            $itemData = $userInfo;
        }

        if ($userInfo instanceof BTreeList) {//userInfo object
            $itemData = $userInfo->getItemsInArray();
        }

        return $itemData;
    }

    /**
     * this function add point for some account,first add history, then calculate
     * final point for account
     * @param type $memberPointType
     * @param type $points
     * @return boolean
     */
    public function addMemberPoint($points, $memberPointAccount = null, $memberPointType = NULL) {

        if ($memberPointAccount == NULL) {
            $memberPointAccount = $this->getCurrentMemberAccount();
        }

        if ($memberPointType == NULL) {
            if ($memberPointAccount != NULL) {
                $memberPointType = $this->getMemberPointTypeByAccount($memberPointAccount);
            } else
                $memberPointType = $this->getCurrentMemberPointType();
        }

        if ($this->checkActionPermit($memberPointType, self::Action_AddPoint, self::Permit_Allow)) {

            $oMemberPointAccount = $this->getMemberPointAccount($memberPointAccount);
            if ($oMemberPointAccount != NULL) {
                $memberPointHistoryTable = new BASpaceSheet('memberPointHistory', $oMemberPointAccount);
                $itemContext = array();
                $itemContext['spaceId'] = Blyn::app()->getActiveSpace()->getId();
                //$itemContext['appId'] = Blyn::app()->getActiveApp()->getId();
                //$itemContext['operationId'] = Blyn::app()->getActiveOperation()->getId();
                $itemContext['userId'] = Blyn::app()->getCurrentUser()->getId();
                $itemContext['accountId'] = $memberPointAccount->getId();
//                $itemContext['operationType'] = $points['operationType'];
                $itemContext['action'] = 'addPoint';
                $itemContext['point'] = $points;
                //$itemContext['finalCharge'] = $points['finalCharge'];
                $itemContext['actionTime'] = time();

                $memberPointHistoryTable->addList($itemContext);

                $accountPoint = $oMemberPointAccount->getItem('memberPoint')->getValue();
                $accountPoint+=$points;
                $oMemberPointAccount->addItem('memberPoint', $accountPoint);

                //return $accountPoint;
                //$memberPointList = $memberPointTable->getList($itemContext);
//                if ($memberPointList != NULL) {
//                    $existPoint = $memberPointList->getItem('point')->getValue();
//                    $newPoint = $existPoint + $points['operationPoint'];
//                    $memberPointList->addItem('point', $newPoint);
//                    return $newPoint;
//                } 
//                else 
                //{
//                    $itemContext['point'] = $points;
                //$itemContext['point'] = $points['finalPoint'];
                //$memberPointList = $memberPointTable->addList($itemContext);
//                $user = Blyn::app()->getCurrentUser();
//                $openid = '';
//                $name = '';
//                $openidAttr = $user->getAttribute('userInfo.openid');
//                if ($openidAttr != NULL) {
//                    $openid = $openidAttr->getValue();
//                }
//                $nameAttr = $user->getAttribute('userInfo.name');
//                if ($nameAttr != NULL) {
//                    $name = $nameAttr->getValue();
//                }
//                //发送微信模板消息
//                $options = array(
//                    'appid' => 'wxd33a8d04590d6e58',
//                    'appsecret' => 'de068491fd6a4f42f122c7d2f10208b2'
//                );
//                $weObj = new BAWechatCooker($options);//oxmO-uNBCGBjzWouLnH44JrmutiA
//                $data = array(
//                    'touser' => $openid,
//                    'template_id' => 'kUcnkiodpWpNQcT6tRKbcuFCNyZSIeg-xBpJkDFCQ1g',
//                    'url' => '',
//                    'topcolor' => '#FF0000',
//                    'data' => array(
//                        'first' => array(
//                            'value' => '尊敬的'.$name.', 您卡号'.$user->getId().'的积分卡最新交易信息',
//                            'color' => '#000000'
//                        ),
//                        'time' => array(
//                            'value' => date("H").'时'.date("i").'分',
//                            'color' => '#000000'
//                        ),
//                        'type' => array(
//                            'value' => '增加',
//                            'color' => '#000000'
//                        ),
//                        'Point' => array(
//                            'value' => $points,
//                            'color' => '#000000'
//                        ),
//                        'From' => array(
//                            'value' => '北京猫爪烤肉',
//                            'color' => '#000000'
//                        ),
//                        'remark' => array(
//                            'value' => '截止'.date("H").'时'.date("i").'分'.'，您的积分卡可用积分为'.$accountPoint.'积分。如有疑问请咨询18883358736',
//                            'color' => '#000000'
//                        ),
//                    )
//                );
//                $res = $weObj->sendTemplateMessage($data);
//                if ($res["errcode"] == 0) {
//                    //发送消息成功
//                }
                return $accountPoint;
            }
        }
        return FALSE;
    }

    public function deductMemberPoint($points, $memberPointAccount = NULL, $memberPointType = NULL) {

        if ($memberPointAccount == NULL) {
            $memberPointAccount = $this->getCurrentMemberAccount();
        }

        if ($memberPointType == NULL) {
            if ($memberPointAccount != NULL) {
                $memberPointType = $this->getMemberPointTypeByAccount($memberPointAccount);
            } else
                $memberPointType = $this->getCurrentMemberPointType();
        }

        if ($this->checkActionPermit($memberPointType, self::Action_DeductPoint, self::Permit_Allow)) {

            $oMemberPointAccount = $this->getMemberPointAccount($memberPointAccount);
            if ($oMemberPointAccount != NULL) {
                $memberPointHistoryTable = new BASpaceSheet('memberPointHistory', $oMemberPointAccount);
                $itemContext = array();
                $itemContext['spaceId'] = Blyn::app()->getActiveSpace()->getId();
                //$itemContext['appId'] = Blyn::app()->getActiveApp()->getId();
                //$itemContext['operationId'] = Blyn::app()->getActiveOperation()->getId();
                $itemContext['userId'] = Blyn::app()->getCurrentUser()->getId();
                $itemContext['accountId'] = $memberPointAccount->getId();
                $itemContext['action'] = 'deductPoint';
                $itemContext['actionTime'] = time();
                $itemContext['point'] = $points;

                $memberPointHistoryTable->addList($itemContext);

                $accountPoint = $oMemberPointAccount->getItem('memberPoint')->getValue();
                $accountPoint-=$points;
                if ($accountPoint < 0) {
                    $accountPoint = 0;
                }
                $oMemberPointAccount->addItem('memberPoint', $accountPoint);

                return $accountPoint;
            }
        }
        return FALSE;
    }

    public function addMemberPointByMoney($money, $memberPointAccount = null, $currencyUnit = 'yuan', $currency = 'rmb') {

        if ($memberPointAccount == NULL) {
            $memberPointAccount = $this->getCurrentMemberPointAccount();
        }

        if (is_numeric($money) && $money > 0) {
            //$discountMoneyInFen = $this->getMoneyInFen($money, $currency, $currencyUnit);
            $memberPointType = $this->getMemberPointTypeByAccount($memberPointAccount);
            $points = $this->populateMemberPointByMoney($money, $memberPointType, $currency, $currencyUnit);
            return $this->addMemberPoint($points, $memberPointAccount);
        }

        return FALSE;
    }

    public function getAddPoint($money, $memberPointAccount = null, $currencyUnit = 'yuan', $currency = 'rmb') {

        if ($memberPointAccount == NULL) {
            $memberPointAccount = $this->getCurrentMemberPointAccount();
        }

        if (is_numeric($money) && $money > 0) {
            //$discountMoneyInFen = $this->getMoneyInFen($money, $currency, $currencyUnit);
            $memberPointType = $this->getMemberPointTypeByAccount($memberPointAccount);
            $points = $this->populateMemberPointByMoney($money, $memberPointType, $currency, $currencyUnit);
            return $points;
        }

        return FALSE;
    }

    public function deductMemberPointByMoney($money, $memberPointAccount = null, $currencyUnit = 'yuan', $currency = 'rmb') {

        if ($memberPointAccount == NULL) {
            $memberPointAccount = $this->getCurrentMemberPointAccount();
        }

        if ($memberPointAccount != NULL && is_numeric($money) && $money > 0) {
            $memberPointType = $this->getMemberPointTypeByAccount($memberPointAccount);
            $discountMoneyInFen = $this->getMoneyInFen($money, $currency, $currencyUnit);
            $points = $this->populateMemberPointByMoney($discountMoneyInFen, $memberPointType);
            return $this->deductMemberPoint($points, $memberPointAccount);
        }

        return FALSE;
    }

    public function populateMemberPointByMoney($money, $memberPointType = null, $currency = 'rmb', $currencyUnit = 'fen', $exchangeRate = NULL) {

        $currentType = $this->getMemberPointType($memberPointType);

        $typeAttributeTable = new BAAttributeSheet($currentType);
        $typeList = $typeAttributeTable->getList(array('itemData' => array('memberPointTypeId' => $currentType->getId())));

        $configCurrency = $typeList->getItem('currency')->getValue();
        if ($exchangeRate == NULL) {
            $exchangeRate = $typeList->getItem('currencyRate')->getValue();
        }
        $configCurrencyUnit = $typeList->getItem('currencyUnit')->getValue();

        $fenMoney = $this->getMoneyInFen($money, $currency, $currencyUnit);

        $onePointMoneyInFen = $this->getMoneyInFen($exchangeRate, $configCurrency, $configCurrencyUnit);

        if (is_numeric($fenMoney) && is_numeric($onePointMoneyInFen) && $onePointMoneyInFen != 0) {
            return $fenMoney / $onePointMoneyInFen;
        }

        return FALSE;
    }

    public function populateMoneyByMemberPoint($memberPoint, $memberPointType = NULL, $currency = 'rmb', $currencyUnit = 'fen', $exchangeRate = null) {

        $currentType = $this->getMemberPointType($memberPointType);

        $typeAttributeTable = new BAAttributeSheet($currentType);
        $typeList = $typeAttributeTable->getList(array('itemData' => array('memberPointTypeId' => $currentType->getId())));

        $configCurrency = $typeList->getItem('currency')->getValue();
        if ($exchangeRate == NULL) {
            $exchangeRate = $typeList->getItem('currencyRate')->getValue();
        }
        $configCurrencyUnit = $typeList->getItem('currencyUnit')->getValue();

        $onePointMoneyInFen = $this->getMoneyInFen($exchangeRate, $configCurrency, $configCurrencyUnit);

        $pointToFenMoney = $memberPoint * $onePointMoneyInFen;

        if ($currency == 'rmb') {
            if ($currencyUnit == 'fen') {
                return $pointToFenMoney;
            }

            if ($currencyUnit == 'jiao') {
                return $pointToFenMoney / 10;
            }

            if ($currencyUnit == 'yuan') {
                return $pointToFenMoney / 100;
            }
        }
    }

    protected function getMoneyInFen($money, $currency = 'rmb', $currencyUnit = 'fen') {

        if ($currency == 'rmb') {
            if ($currencyUnit == 'fen') {
                return $money;
            }
            if ($currencyUnit == 'jiao') {
                return $money * 10;
            }
            if ($currencyUnit == 'yuan') {
                return $money * 100;
            }
        }
    }

    protected function getMemberPointTypeRoot() {
        //$eventCooker = new BAEventCooker();
        //$event = $eventCooker->getCurrentEvent();
        $category = new BACategory();
        $categoryRoot = $category->getRootNode();
        $memberPointTypeRoot = $categoryRoot->getChild('memberPointType');
        if ($memberPointTypeRoot == NULL) {
            $memberPointTypeRoot = $categoryRoot->addChild('memberPointType');
        }
        return $memberPointTypeRoot;
    }

    /**
     * 
     * @param string format, can be aliasList, nameList,objectList,arrayList
     * @param type $data
     * @return type
     */
    public function getMemberPointTypeList($format = 'aliasList', $permit = null, $data = NULL) {

        $memberPointTypeRoot = $this->getMemberPointTypeRoot();

        $children = $memberPointTypeRoot->getChildrenAsLeaf();

        if (strtolower($format) == 'objectlist') {
            return $children;
        }

        $list = array();

        foreach ($children as $id => $type) {
            $savedPermit = $this->getMemberPointTypePermit($id);

            if ($permit == NULL || $savedPermit == $permit) {
                if (strtolower($format) == 'arraylist') {
                    $item = array();
                    $item['id'] = $id;
                    $item['name'] = $typeName = $type->getName();
                    $item['alias'] = $type->getValue();

                    $tNames = explode('_', $typeName);
                    if (count($tNames) > 1) {
                        $appName = $tNames[0];
                    } else {
                        $appName = 'BWeMember';
                    }
                    $item['appName'] = $appName;
                    $item['permit'] = $this->getMemberPointTypePermit($id);

                    $list[$id] = $item;
                }
                if (strtolower($format) == 'namelist') {
                    $list[$id] = $type->getName();
                }
                if (strtolower($format) == 'aliaslist') {
                    $list[$id] = $type->getValue();
                }
            }
        }

        return $list;
    }

    public function getActionPermitList($format = 'arrayList', $memberPointType = null, $data = null) {

        $eventCooker = new BAEventCooker();
        $currentEvent = $eventCooker->getCurrentEvent();
        $memberPointTypePermitTable = new BASpaceSheet('memberPointTypePermit', $currentEvent);

        $itemContext = array();
        $itemContext['spaceId'] = Blyn::app()->getActiveSpace()->getId();
        $itemContext['permit'] = self::Permit_Allow;

        $typeIdList = $memberPointTypePermitTable->getValueList('memberPointTypeId', array('itemData' => $itemContext));

        $memberPointTable = new BASpaceSheet('memberPointPermit', $currentEvent);

        $itemData = array();
        $itemData['spaceId'] = Blyn::app()->getActiveSpace()->getId();

        //only allowed type can show in list
        $aTypeList = array();
        foreach ($typeIdList as $typeId => $count) {
            array_push($aTypeList, $typeId);
        }
        $itemData['memberPointTypeId'] = $aTypeList;

        $oType = $this->getMemberPointType($memberPointType);

        if ($oType != NULL) {
            //only show specific type
            $oTypeId = $oType->getId();
            if (in_array($oTypeId, $aTypeList)) {
                $itemData['memberPointTypeId'] = $oType->getId();
            }
        }

        $view = $memberPointTable->getView(array('itemData' => $itemData));
        $eventCooker = new BAEventCooker();

        $list = array();
        foreach ($view as $id => $permit) {
            if (strtolower($format) == 'arraylist') {
                $item = array();
                $item['id'] = $id;
                $item['permit'] = $permit->getItem('permit')->getValue();
                $typeId = $permit->getItem('memberPointTypeId')->getValue();
                $typeName = $permit->getItem('memberPointTypeName')->getValue();
                $tNames = explode('_', $typeName);
                $appName = $tNames[0];
                $item['appName'] = $appName;
                $item['typeAlias'] = $this->getMemberPointType($typeId)->getValue();
                $item['action'] = $permit->getItem('action')->getValue();
                $item['operationName'] = $permit->getItem('operationName')->getValue();
                $item['eventTypeAlias'] = $permit->getItem('eventTypeAlias')->getValue();
                $list[$id] = $item;
            }

            if (strtolower($format) == 'stringlist') {
                $list[$id] = $permit->getItem('permit')->getValue();
            }
        }

        return $list;
    }

    public function getActionAdminList($data = NULL) {
        return array();
    }

    public function getCurrentMemberPointType($data = NULL) {

        $memberPointTypeId = $this->activeLink->getLinkVariable('memberPointTypeId');

        if (is_numeric($memberPointTypeId) && $memberPointTypeId > 0) {
            //update value in context variable
            Blyn::app()->getUIManager()->getCurrentScreen()->addContextVariable('memberPointTypeId', $memberPointTypeId);
        } else {
            if ($memberPointTypeId == NULL) {
                //try to find from context variable
                $memberPointTypeId = Blyn::app()->getUIManager()->getCurrentScreen()->getContextVariable('memberPointTypeId');
            }
        }

        if (is_numeric($memberPointTypeId) && $memberPointTypeId > 0) {
            $memberPointType = new BACategory($memberPointTypeId);
            return $memberPointType;
        }
        return FALSE;
    }

    public function getCurrentMemberPointAccount($data = NULL) {

        $memberPointAccountId = $this->activeLink->getLinkVariable('memberPointAccountId');

        if (is_numeric($memberPointAccountId) && $memberPointAccountId > 0) {
            //update value in context variable
            Blyn::app()->getUIManager()->getCurrentScreen()->addContextVariable('memberPointAccountId', $memberPointAccountId);
        } else {
            if ($memberPointAccountId == NULL) {
                //try to find from context variable
                $memberPointAccountId = Blyn::app()->getUIManager()->getCurrentScreen()->getContextVariable('memberPointAccountId');
            }
        }

        if (is_numeric($memberPointAccountId) && $memberPointAccountId > 0) {
            $accountTable = new BASpaceSheet('memberPointAccount');
            $memberPointAccount = $accountTable->getListById($memberPointAccountId);
            return $memberPointAccount;
        }
        return FALSE;
    }

    public function getMemberPointTypeByAccount($memberPointAccount) {

        $oAccount = $this->getMemberPointAccount($memberPointAccount);

        if ($oAccount instanceof BTreeList) {
            $memberPointTypeId = $oAccount->getItem('memberPointTypeId')->getValue();
            if (is_numeric($memberPointTypeId) && $memberPointTypeId > 0) {
                return new BACategory($memberPointTypeId);
            }
        }
        return FALSE;
    }

    public static function getGenderAlias($gender) {
        if (strtolower($gender) == 'lady')
            return '女士';
        if (strtolower($gender) == 'mister')
            return '先生';
        if (strtolower($gender) == 'boy')
            return '男孩';
        if (strtolower($gender) == 'girl')
            return '女孩';
    }

    /**
     * this function use to show add/modify memberpoint type view
     * @param type $data
     */
    public function onShowAddMemberPointType($data = NULL) {

        $typeId = $this->activeLink->getLinkVariable('memberPointTypeId');

        $model = new BDynamicFormModel();
        $typeNameField = 'media_name_add_memberPointType';
        $typeAliasField = 'media_alias_add_memberPointType';
        $currencyRateField = 'media_currencyRate_add_memberPointType';
        $currencyField = 'media_currency_add_memberPointType';
        $currencyUnitField = 'media_currencyUnit_add_memberPointType';
        $discountRateField = 'media_discountRate_add_memberPointType';

        $model->addField($typeNameField);
        $model->addField($typeAliasField);
        $model->addField($currencyField);
        $model->addField($currencyUnitField);
        $model->addField($currencyRateField);
        $model->addField($discountRateField);

        $typeTable = new BAAttributeSheet($this->getMemberPointType($typeId));

        $type = NULL;
        if ($typeId != NULL && $typeId > 0) {

            $type = $this->getMemberPointType($typeId);

            $typeList = $typeTable->getList(array('itemData' => array('memberPointTypeId' => $typeId)));

            //将已经存在的数据放进MODEL里面
            if ($typeList->getItem('name') != NULL)
                $model->$typeNameField = $typeList->getItem('name')->getValue();
            if ($typeList->getItem('alias') != NULL)
                $model->$typeAliasField = $typeList->getItem('alias')->getValue();
            if ($typeList->getItem('currencyRate') != NULL)
                $model->$currencyRateField = $typeList->getItem('currencyRate')->getValue();
            if ($typeList->getItem('currency') != NULL)
                $model->$currencyField = $typeList->getItem('currency')->getValue();
            if ($typeList->getItem('currencyUnit') != NULL)
                $model->$currencyUnitField = $typeList->getItem('currencyUnit')->getValue();
            if ($typeList->getItem('discountRate') != NULL)
                $model->$currencyUnitField = $typeList->getItem('discountRate')->getValue();
        }
        /* else {
          //below code create a temporary type

          $listId = 'list_' . Blyn::app()->getActiveOperation()->getId() . '_' . Blyn::app()->getCurrentUser()->getId();
          $type = $typeTable->getList(array('name' => $listId));
          if ($type == NULL) {
          $type = $typeTable->getNewList(NULL, $listId);
          }
          }
         * 
         */

        $this->updateControl->addRenderView('addMemberPointType', 'memberPointType_add', array(
            'model' => $model,
            'typeNameField' => $typeNameField,
            'typeAliasField' => $typeAliasField,
            'currencyField' => $currencyField,
            'currencyUnitField' => $currencyUnitField,
            'currencyRateField' => $currencyRateField,
            'discountRateField' => $discountRateField,
            'memberPointTypeId' => $typeId,
            'memberPointType' => $type
        ));
    }

    public function onShowMemberPointTypeList($control = NULL) {
        //$opName = Blyn::app()->getActiveOperation()->getName();
        if (!$control instanceof BUIControl) {
            $control = $this->updateControl;
        }

        $eventHome = $this->getCurrentEventHome();

        //default permit 
        $permit = self::Permit_Allow;
        $listView = 'memberPointType_list_' . $eventHome;
        if ($eventHome == 'admin')
            $permit = NULL; //for admin, show all list
        $mptList = $this->getMemberPointTypeList('arrayList', $permit);
        $control->addRenderView('showMemberPointList', $listView, array('memberPointTypeList' => $mptList));
    }

    public function onToggleMemberPointTypePermit($data = NULL) {
        $memberPointTypeId = $this->activeLink->getLinkVariable('memberPointTypeId');
        $permitTable = new BASpaceSheet('memberPointTypePermit');
        $itemContext = array();
        $itemContext['memberPointTypeId'] = $memberPointTypeId;
        $itemContext['spaceId'] = Blyn::app()->getActiveSpace()->getId();

        $list = $permitTable->getList(array('itemData' => $itemContext));

        //if not exist, add allow permit 
        if ($list == NULL) {
            $this->addMemberPointTypePermit($memberPointTypeId);
        } else {
            $oldPermit = $list->getItem('permit')->getValue();
            if ($oldPermit == self::Permit_Allow) {
                $list->addItem('permit', self::Permit_Deny);
            } else {
                $list->addItem('permit', self::Permit_Allow);
            }
        }

        $this->onShowMemberPointTypeList();
    }

    public function onShowMemberPointActionPermit($data = NULL) {
        $actionPermitList = $this->getActionPermitList();
        $this->updateControl->addRenderView('permitList', 'memberPointAction_permit_admin', array(
            'memberPointActionPermitList' => $actionPermitList));
    }

    public function onShowMemberPointActionAdmin($data = NULL) {
        $actionAdminList = $this->getActionAdminList();
        $this->updateControl->addRenderView('adminList', 'memberPointAction_admin', array(
            'memberPointActionAdminList' => $actionAdminList));
    }

    public function onShowMemberPointAccountAddDeductSummary($data = NULL) {
        $currentType = $this->getCurrentMemberPointType();

//        $mpList = $this->getMemberPointAccountList($currentType);
        if ($data != NULL && is_array($data)) {
            $this->updateControl->addRenderView(
                    'memberPointAccountAddDeductSummary', 'memberPoint_add_deduct_summary', array(
                'data' => $data));
        }
    }

    public function onShowMemberPointAccountList($data = NULL) {
        $currentType = $this->getCurrentMemberPointType();

        $mpList = $this->getMemberPointAccountList($currentType);

        $this->updateControl->addRenderView(
                'memberPointAccountList', 'memberPointAccount_list_manager', array(
            'memberPointAccountList' => $mpList));
    }

    public function onShowCurrentMemberPointManagement($data = NULL) {

        $this->updateControl->addRenderView(
                'currentMemberPointManagement', 'memberPoint_member_home', array(
            'data' => $data));
    }

    public function onShowCurrentMemberPointAccountList($data = NULL) {
        $memberPointAccountList = $this->getCurrentMemberPointAccountList();
        $userCooker = new BAUserCooker();
        foreach ($memberPointAccountList as $id => $list) {
            if ($list->getItem('userInfoId') != NULL) {
                $userInfoId = $list->getItem('userInfoId')->getValue();
                $oUserInfo = $userCooker->getUserInfoById($userInfoId);
                $account['userInfoId'] = $list->getItem('userInfoId')->getValue();
                if ($oUserInfo->getItem('mobile') != NULL) {
                    $account['mobile'] = $oUserInfo->getItem('mobile')->getValue();
                }
                if ($oUserInfo->getItem('email') != NULL)
                    $account['email'] = $oUserInfo->getItem('email')->getValue();
                $name = '';
                if ($oUserInfo->getItem('familyName') != NULL) {
                    $name = $oUserInfo->getItem('familyName')->getValue();
                }
                if ($oUserInfo->getItem('surName') != NULL) {
                    $name .= $oUserInfo->getItem('surName')->getValue();
                }
                $account['userName'] = $name;
                if ($oUserInfo->getItem('gender') != NULL)
                    $account['gender'] = $oUserInfo->getItem('gender')->getValue();
            }
            if ($list->getItem('accountId') != NULL)
                $account['accountId'] = $list->getItem('accountId')->getValue();
            if ($list->getItem('lastChangeTime') != NULL)
                $account['lastChangeTime'] = $list->getItem('lastChangeTime')->getValue();
            if ($list->getItem('memberPoint') != NULL)
                $account['memberPoint'] = $list->getItem('memberPoint')->getValue();
            if ($list->getItem('memberPointTypeId') != NULL)
                $account['memberPointTypeId'] = $list->getItem('memberPointTypeId')->getValue();

            $accountId = $account['accountId'];
            $userName = '';
            if (isset($account['userName']))
                $userName = $account['userName'];
            $gender = '--';
            if (isset($account['gender']))
                $gender = $account['gender'];
            $userInfo = '';
            $mobile = '--';
            if (isset($account['mobile'])) {
                $mobile = $account['mobile'];
                $userInfo .=';' . $account['mobile'];
            }
            if (isset($account['memberPoint']))
                $point = $account['memberPoint'];
            else
                $point = 0;
            $changeTime = $account['lastChangeTime'];
            $changeTime = date('y/m/d h:i:sa', ($changeTime));
            $memberPointTypeId = $account['memberPointTypeId'];
        }

//        $this->updateControl->addRenderView(
//                'memberPointAccountList', 'memberPointAccount_list_manager', array(
//            'memberPointAccountList' => $mpList));
//        getAjaxLink(array('name' => '记录', 'id' => 'showMemberPointHistory'), array(
//                                    'cooker' => 'BAMemberPoint@showMemberPointHistoryByType', 'accountIdNumber' => $accountId,
//                                    'memberPointAccountId' => $id, 'memberPointTypeId' => $memberPointTypeId));

        if (isset($memberPointTypeId)) {
            $currentType = $this->getMemberPointType($memberPointTypeId);
        }
        $mpList = '';
        $currentTypeId = '';
        if (isset($accountId) && $accountId > 0 && $currentType != NULL) {
            $mpList = $this->getMemberPointAccountHistory($currentType, $accountId); //zxm
        }
        if (isset($currentType)) {
            $currentTypeId = $currentType->getId();
        }
        $this->updateControl->addRenderView(
                'memberPointHistoryList', 'memberPoint_history_member', array(
            'memberPointHistoryList' => $mpList,
            'memberPointTypeId' => $currentTypeId
        ));
    }

    public function onShowAddMemberPointAccount($data = NULL) {

        $accountId = $this->activeLink->getLinkVariable('memberPointAccountId');

        $memberPointType = $this->getCurrentMemberPointType();

        $model = new BDynamicFormModel();
        $familyNameField = 'media_familyName_add_userInfo';
        $surNameField = 'media_surName_add_userInfo';
        $emailField = 'media_email_add_userInfo';
        $mobileField = 'media_mobile_add_userInfo';
        $genderField = 'media_gender_add_userInfo';
        $birthField = 'media_birth_add_userInfo';
        $fixedCardIdField = 'media_fixedCardId_add_memberPointAccount';
        $accountIdField = 'media_accountId_add_memberPointAccount';

        $model->addField($accountIdField);
        $model->addField($familyNameField);
        $model->addField($surNameField);
        $model->addField($emailField);
        $model->addField($mobileField);
        $model->addField($genderField);
        $model->addField($birthField);
        $model->addField($fixedCardIdField);

        if (is_array($data) && $data != NULL) {
            if (isset($data['mobile']))
                $model->$mobileField = $data['mobile'];
            if (isset($data['email']))
                $model->$emailField = $data['email'];
            if (isset($data['familyName']))
                $model->$familyNameField = $data['familyName'];
            if (isset($data['surName']))
                $model->$surNameField = $data['surName'];
            if (isset($data['gender']))
                $model->$genderField = $data['gender'];
            if (isset($data['birth']))
                $model->$birthField = $data['birth'];
            if (isset($data['fixedCardId']))
                $model->$fixedCardIdField = $data['fixedCardId'];
        }

        $accountTable = new BASpaceSheet('memberPointAccount');

        if ($accountId != NULL && $accountId > 0) {

            $account = $accountTable->getListById($accountId);
            if ($account->getItem('userInfoId') != NULL) {
                $userInfoId = $account->getItem('userInfoId')->getValue();
                $userCooker = new BAUserCooker();
                $oUserInfo = $userCooker->getUserInfoById($userInfoId);
            }

            //reset list name
            if ($account->getName() == 'list_' . Blyn::app()->getActiveOperation()->getId() . '_' . Blyn::app()->getCurrentUser()->getId()) {
                $aId = $account->getId();
                $account->name = 'list' . $aId;
                $account->save();
            }

            //将已经存在的活动数据放进MODEL里面
            if (isset($oUserInfo)) {
                if ($oUserInfo->getItem('email') != NULL)
                    $model->$emailField = $oUserInfo->getItem('email')->getValue();
                if ($oUserInfo->getItem('familyName') != NULL)
                    $model->$familyNameField = $oUserInfo->getItem('familyName')->getValue();
                if ($oUserInfo->getItem('surName') != NULL)
                    $model->$surNameField = $oUserInfo->getItem('surName')->getValue();
                if ($oUserInfo->getItem('mobile') != NULL)
                    $model->$mobileField = $oUserInfo->getItem('mobile')->getValue();
                if ($oUserInfo->getItem('gender') != NULL)
                    $model->$genderField = $oUserInfo->getItem('gender')->getValue();
                if ($oUserInfo->getItem('birth') != NULL)
                    $model->$birthField = $oUserInfo->getItem('birth')->getValue();
            }
            if ($account->getItem('fixedCardId') != NULL)
                $model->$fixedCardIdField = $account->getItem('fixedCardId')->getValue();
            if ($account->getItem('accountId') != NULL)
                $model->$accountIdField = $account->getItem('accountId')->getValue();

            //add attribute data into model
            //$attrributeControl = new BUIAttribute();
            //$attributeTable = new BPProductSheet('accountAttribute', $account);
            //$attrributeControl->populateModelFromAttribute($model, $account, $attributeTable, 'add_account');
        }else {
            //below code create a temporary account
            $account = $accountTable->getTempList();
            /*
              $listId = 'list_' . Blyn::app()->getActiveOperation()->getId() . '_' . Blyn::app()->getCurrentUser()->getId();
              $account = $accountTable->getList(array('name' => $listId));
              if ($account == NULL) {
              $account = $accountTable->getNewList(NULL, $listId);
              }
             * 
             */
        }

        //$accountId = $account->getId();
        $viewData = array(
            'model' => $model,
            'familyNameField' => $familyNameField,
            'surNameField' => $surNameField,
            'emailField' => $emailField,
            'mobileField' => $mobileField,
            'genderField' => $genderField,
            'birthField' => $birthField,
            'fixedCardIdField' => $fixedCardIdField,
            'accountIdField' => $accountIdField,
            'memberPointTypeId' => $memberPointType->getId(),
            'memberPointAccount' => $account,
            'memberPointAccountId' => $accountId);
        if (is_array($data) && $data != NULL) {
            $viewData += $data;
        }
        $viewData['viewData'] = $viewData;
        $this->updateControl->addRenderView('addMemberPointAccount', 'memberPointAccount_add', $viewData);
    }

    public function onAddMemberPointAccount($data = NULL) {

        $accountId = $this->activeLink->getLinkVariable('memberPointAccountId');

        $accountData = $this->postManager->populatePostDataByIndex($this->postData, 'add_memberPointAccount');
        $userData = $this->postManager->populatePostDataByIndex($this->postData, 'add_userInfo');

        $memberPointType = $this->getCurrentMemberPointType();

        $account = NULL;
        $userCooker = new BAUserCooker();

        $mobileChanged = TRUE;
        $emailChanged = TRUE;

        if ($accountId > 0) {
            $accountTable = new BASpaceSheet('memberPointAccount');
            $account = $accountTable->getListById($accountId);
            if ($account->getItem('userInfoId') != NULL) {
                $userInfoId = $account->getItem('userInfoId')->getValue();
                $savedUserInfo = $userCooker->getUserInfoById($userInfoId);
                $savedUserData = $savedUserInfo->getItemsInArray();
                if (isset($savedUserData['mobile']) && isset($userData['mobile'])) {
                    if ($savedUserData['mobile'] == $userData['mobile'])
                        $mobileChanged = FALSE;
                }
                if (isset($savedUserData['email']) && isset($userData['email'])) {
                    if ($savedUserData['email'] == $userData['email'])
                        $emailChanged = FALSE;
                }
            }
            //$itemData['accountId'] = $accountId + 20121212;
        } else {
            $account = $this->getMemberPointAccount($userData, $memberPointType);
        }

        if ($account != NULL) { //说明提供的用户数据已经被用了
            $existUserData = $userCooker->haveExistUserInfo($userData);

            if (isset($existUserData['mobile']) && $mobileChanged) {
                $errorMessages['wrongMobile'] = $userData['mobile'] . '手机号已被使用！';
            }
            if (isset($existUserData['email']) && $emailChanged) {
                $errorMessages['wrongEmail'] = $userData['email'] . 'Email已被使用！';
            }
            if (isset($errorMessages) && $errorMessages != NULL) {
                $viewData = $errorMessages;
                $viewData+=$accountData;
                $viewData+=$userData;
                $this->onShowAddMemberPointAccount($viewData);
                return;
            }
        }

        $account = $this->addMemberPointAccount($memberPointType, $userData, $accountData, $account);

        $this->onShowMemberPointAccountList();
    }

    public function onAddMemberPointType($data = NULL) {

        $typeId = $this->activeLink->getLinkVariable('memberPointTypeId');

        $mediaList = $this->postManager->populateMediaListFromPostData($this->postData, 'add_memberPointType');

        $itemData = array();
        foreach ($mediaList as $media) {
            $name = $media->name;
            $value = $media->content;
            if ($value != NULL || $value != '') {
                $itemData[$name] = $value;
            }
        }

        $type = $this->addMemberPointType($itemData['name'], $itemData['alias'], $itemData);

        $this->onShowMemberPointTypeList();
    }

    public function manageMemberPointAccount($memberPointType, $userInfo) {

        $memberPointType = $this->getMemberPointType($memberPointType);

        $memberPointAccountTable = new BASpaceSheet('memberPointAccount', $memberPointType);

        $itemData = $this->populateUserInfo($userInfo);

        if (empty($itemData))
            return FALSE;

        $list = $memberPointAccountTable->getListById($itemData['accountId']);
        if ($list != NULL) {
            $itemData['accountId'] = 20121212 + $list->getId();
            $itemData['lastChangeTime'] = time();

            if ($list instanceof BTreeList) {
                $list->addItems($itemData);
                return $list;
            }
        }

        return FALSE;
    }

    public function onManageMemberPointAccount($data = NULL) {

        $accountId = $this->activeLink->getLinkVariable('memberPointAccountId');

        $mediaList = $this->postManager->populateMediaListFromPostData($this->postData, 'add_memberPointAccount');

        $itemData = array();
        $itemData['accountId'] = $accountId; // + 20121212;
        foreach ($mediaList as $media) {
            $name = $media->name;
            $value = $media->content;
            if ($value != NULL || $value != '') {
                $itemData[$name] = $value;
            }
        }

        $memberPointType = $this->getCurrentMemberPointType();

        $account = $this->manageMemberPointAccount($memberPointType, $itemData);
        $this->onShowMemberPointAccountList();
    }

    public function onShowManageMemberPoint() {
        $accountId = $this->activeLink->getLinkVariable('memberPointAccountId');

        $memberPointType = $this->getCurrentMemberPointType();

        $model = new BDynamicFormModel();
        $userNameField = 'media_userName_add_memberPointAccount';
        $emailField = 'media_email_add_memberPointAccount';
        $mobileField = 'media_mobile_add_memberPointAccount';
        $genderField = 'media_gender_add_memberPointAccount';
        $accountIdField = 'media_accountId_add_memberPointAccount';

        $model->addField($userNameField);
        $model->addField($emailField);
        $model->addField($mobileField);
        $model->addField($genderField);
        $model->addField($accountIdField);

        $accountTable = new BASpaceSheet('memberPointAccount');

        if ($accountId != NULL && $accountId > 0) {

            $account = $accountTable->getListById($accountId);

            //将已经存在的活动数据放进MODEL里面
            if ($account->getItem('email') != NULL)
                $model->$emailField = $account->getItem('email')->getValue();
            if ($account->getItem('userName') != NULL)
                $model->$userNameField = $account->getItem('userName')->getValue();
            if ($account->getItem('mobile') != NULL)
                $model->$mobileField = $account->getItem('mobile')->getValue();
            if ($account->getItem('gender') != NULL)
                $model->$genderField = $account->getItem('gender')->getValue();
            if ($account->getItem('accountId') != NULL)
                $model->$accountIdField = $account->getItem('accountId')->getValue();

            //add attribute data into model
            //$attrributeControl = new BUIAttribute();
            //$attributeTable = new BPProductSheet('accountAttribute', $account);
            //$attrributeControl->populateModelFromAttribute($model, $account, $attributeTable, 'add_account');
        }else {
            //below code create a temporary account
            $listId = 'list_' . Blyn::app()->getActiveOperation()->getId() . '_' . Blyn::app()->getCurrentUser()->getId();
            $account = $accountTable->getList(array('name' => $listId));
            if ($account == NULL) {
                $account = $accountTable->getNewList(NULL, $listId);
            }
        }

        $accountId = $account->getId();

        $this->updateControl->addRenderView('manageMemberPointAccount', 'memberPointAccount_manage', array(
            'model' => $model,
            'userNameField' => $userNameField,
            'emailField' => $emailField,
            'mobileField' => $mobileField,
            'genderField' => $genderField,
            'accountIdField' => $accountIdField,
            'memberPointTypeId' => $memberPointType->getId(),
            'memberPointAccount' => $account,
            'memberPointAccountId' => $accountId));
    }

    public function onAddDeductMemberPoint($data = NULL) {
        $accountId = $this->activeLink->getLinkVariable('memberPointAccountId');
        $currentPoint = $this->activeLink->getLinkVariable('currentPoint');

        $mediaList = $this->postManager->populateMediaListFromPostData($this->postData, 'add_memberPoint');

        $itemData = array();
        $itemData['accountId'] = $accountId; // + 20121212;
        foreach ($mediaList as $media) {
            $name = $media->name;
            $value = $media->content;
            if ($value != NULL || $value != '') {
                $itemData[$name] = $value;
            }
        }

        $accountData = array();
//        if ($itemData['operationType'] == '1') //add
//            $itemData['operationPoint'] = $currentPoint + $itemData['operationPoint'];
//        else //deduct
//            $itemData['operationPoint'] = $currentPoint - $itemData['operationPoint'];
//
//        if ($itemData['operationPoint'] < 0)
//            $itemData['operationPoint'] = 0;
        $memberPointType = $this->getCurrentMemberPointType();

        $consumptionField = $itemData['consumption'];
        $operationPointField = $itemData['operationPoint'];
        $exchangeRate = $this->getExchangeRate($memberPointType->getId());

        $redeem = $operationPointField * $exchangeRate['currencyRate'];
        if ($exchangeRate['currencyUnit'] == 'jiao')
            $redeem = $redeem * 0.1;
        else if ($exchangeRate['currencyUnit'] == 'fen')
            $redeem = $redeem * 0.01;

        $finalChargeField = number_format(($consumptionField - $redeem) * (1 - 0.01 * $exchangeRate['discountRate']), 2, '.', ',');
        if ($exchangeRate['currencyUnit'] == 'jiao')
            $finalPointField = number_format($finalChargeField * 10.0 / $exchangeRate['currencyRate'] + $currentPoint - $operationPointField, 0, '', ',');
        else if ($exchangeRate['currencyUnit'] == 'fen')
            $finalPointField = number_format($finalChargeField * 100.0 / $exchangeRate['currencyRate'] + $currentPoint - $operationPointField, 0, '', ',');
        else
            $finalPointField = number_format($finalChargeField / $exchangeRate['currencyRate'] + $currentPoint - $operationPointField, 0, '', ',');

//        $finalPointField = number_format($finalChargeField * $exchangeRate + $currentPoint, 0, '', ',');

        $itemData['finalCharge'] = $finalChargeField;
        $itemData['operationPoint'] = $operationPointField;
        $itemData['finalPoint'] = $finalPointField;

        //$memberPointType = $this->getCurrentMemberPointType();

        $accountPoint = $this->addMemberPoint($memberPointType, $itemData);

        //update the point in memberPointAccount table?        
        $accountData['accountId'] = $accountId;
        $accountData['memberPoint'] = $accountPoint;
        $account = $this->manageMemberPointAccount($memberPointType, $accountData);

        $data = array();
        $data['memberPointTypeId'] = $memberPointType->getId();
        $data['accountIdField'] = $accountId;
        $data['consumptionField'] = $consumptionField;
        $data['operationPointField'] = $operationPointField;
        $data['finalChargeField'] = $finalChargeField;
        $data['finalPointField'] = $finalPointField;
        $this->onShowMemberPointAccountAddDeductSummary($data);
    }

    public function onShowAddDeductMemberPoint($data = NULL) {
        $accountId = $this->activeLink->getLinkVariable('memberPointAccountId');
        $accountIdNumber = $this->activeLink->getLinkVariable('accountIdNumber');
        $currentPoint = $this->activeLink->getLinkVariable('currentPoint');

        $memberPointType = $this->getCurrentMemberPointType();

        $model = new BDynamicFormModel();

        $accountIdField = 'media_accountId_add_memberPoint';
        $operationTypeField = 'media_operationType_add_memberPoint';
        $operationPointField = 'media_operationPoint_add_memberPoint';
        $pointField = 'media_currentPoint_add_memberPoint';
        $consumptionField = 'media_consumption_add_memberPoint';

        $model->addField($accountIdField);
        $model->addField($operationTypeField);
        $model->addField($operationPointField);
        $model->addField($consumptionField);
        $model->addField($pointField);

        $memberPointAddDeductTable = new BASpaceSheet('memberPoint');

        $model->$accountIdField = $accountIdNumber;
        if ($currentPoint == 0)
            $currentPoint = '0 ';
        $model->$pointField = $currentPoint;
        $model->$operationPointField = $currentPoint;

        $this->updateControl->addRenderView('memberPoint_add_deduct', 'memberPoint_add_deduct', array(
            'model' => $model,
            'pointField' => $pointField,
            'accountIdField' => $accountIdField,
            'operationTypeField' => $operationTypeField,
            'operationPointField' => $operationPointField,
            'consumptionField' => $consumptionField,
            'memberPointTypeId' => $memberPointType->getId(),
            'memberPointAccountId' => $accountId,
            'currentPoint' => $currentPoint
        ));
    }

    public function onShowMemberPointAccountDetail() {
        $accountId = $this->activeLink->getLinkVariable('memberPointAccountId');

        $memberPointType = $this->getCurrentMemberPointType();

        $model = new BDynamicFormModel();
        $userNameField = 'media_userName_add_memberPointAccount';
        $emailField = 'media_email_add_memberPointAccount';
        $mobileField = 'media_mobile_add_memberPointAccount';
        $genderField = 'media_gender_add_memberPointAccount';
        $accountIdField = 'media_accountId_add_memberPointAccount';

        $model->addField($userNameField);
        $model->addField($emailField);
        $model->addField($mobileField);
        $model->addField($genderField);
        $model->addField($accountIdField);

        $accountTable = new BASpaceSheet('memberPointAccount');

        if ($accountId != NULL && $accountId > 0) {

            $account = $accountTable->getListById($accountId);

            //将已经存在的活动数据放进MODEL里面
            if ($account->getItem('email') != NULL)
                $model->$emailField = $account->getItem('email')->getValue();
            if ($account->getItem('userName') != NULL)
                $model->$userNameField = $account->getItem('userName')->getValue();
            if ($account->getItem('mobile') != NULL)
                $model->$mobileField = $account->getItem('mobile')->getValue();
            if ($account->getItem('gender') != NULL)
                $model->$genderField = $account->getItem('gender')->getValue();
            if ($account->getItem('accountId') != NULL)
                $model->$accountIdField = $account->getItem('accountId')->getValue();

            //add attribute data into model
            //$attrributeControl = new BUIAttribute();
            //$attributeTable = new BPProductSheet('accountAttribute', $account);
            //$attrributeControl->populateModelFromAttribute($model, $account, $attributeTable, 'add_account');
        }else {
            //below code create a temporary account
            $listId = 'list_' . Blyn::app()->getActiveOperation()->getId() . '_' . Blyn::app()->getCurrentUser()->getId();
            $account = $accountTable->getList(array('name' => $listId));
            if ($account == NULL) {
                $account = $accountTable->getNewList(NULL, $listId);
            }
        }

        $accountId = $account->getId();

        $this->updateControl->addRenderView('manageMemberPointAccount', 'memberPointAccount_manage', array(
            'model' => $model,
            'userNameField' => $userNameField,
            'emailField' => $emailField,
            'mobileField' => $mobileField,
            'genderField' => $genderField,
            'accountIdField' => $accountIdField,
            'memberPointTypeId' => $memberPointType->getId(),
            'memberPointAccount' => $account,
            'memberPointAccountId' => $accountId));
    }

    public function onShowMemberPointHistory() {
        $currentType = $this->getCurrentMemberPointType();
        $accountId = $this->activeLink->getLinkVariable('memberPointAccountId');
//        $accountNumber = $this->activeLink->getLinkVariable('accountIdNumber');

        $mpList = $this->getMemberPointAccountHistory($currentType, $accountId);

        $this->updateControl->addRenderView(
                'memberPointHistoryList', 'memberPoint_history_manager', array(
            'memberPointHistoryList' => $mpList,
            'memberPointTypeId' => $currentType->getId()
        ));
    }

    public function onShowMemberPointHistoryByType() {
        $accountId = $this->activeLink->getLinkVariable('memberPointAccountId');
        $memberPointTypeId = $this->activeLink->getLinkVariable('memberPointTypeId');
        $currentType = $this->getMemberPointType($memberPointTypeId);

        if ($accountId > 0 && $currentType != NULL) {
            $mpList = $this->getMemberPointAccountHistory($currentType, $accountId);

            $this->updateControl->addRenderView(
                    'memberPointHistoryList', 'memberPoint_history_manager', array(
                'memberPointHistoryList' => $mpList,
                'memberPointTypeId' => $currentType->getId()
            ));
        }
    }

    //working method...
    public function getExchangeRate($data = NULL) {
        $rate = array();
        $typeTable = new BASpaceSheet('memberPointType', $this->getCurrentEvent());
        $type = NULL;
        $typeId = $data;
        if ($typeId != NULL && $typeId > 0) {
            $type = $this->getMemberPointType($typeId);
            $typeList = $typeTable->getList(array('itemData' => array('memberPointTypeId' => $typeId)));

            $rate['currencyUnit'] = $typeList->getItem('currencyUnit')->getValue();
            $rate['currencyRate'] = $typeList->getItem('currencyRate')->getValue();
            $rate['discountRate'] = $typeList->getItem('discountRate')->getValue();
        }

        return $rate;
    }

    public static function getCurrencyData($data = NULL) {
        return array('rmb' => '人民币');
    }

    public static function getCurrencyUnitData($currency = 'rmb', $data = null) {

        if (strtolower($currency) == 'rmb') {
            return array(
                'fen' => '分',
                'jiao' => '角',
                'yuan' => '元'
            );
        }
    }

    public function onSearchMemberPointList($data = NULL) {
//        $currentType = $this->getCurrentMemberPointType();
//        $accountId = $this->activeLink->getLinkVariable('searchCondition');
//        $model = $this->activeLink->getLinkVariable('model');
//        $searchText = $model->$searchText;
        $searchText = $this->activeLink->getLinkVariable('searchText');
        $mediaList = $this->postManager->populateMediaListFromPostData($this->postData, 'searchText');

        $itemData = array();
        $itemData['accountId'] = $searchText; // + 20121212;
        foreach ($mediaList as $media) {
            $name = $media->name;
            $value = $media->content;
            if ($value != NULL || $value != '') {
                $itemData[$name] = $value;
            }
        }

        $mpList = $this->getMemberPointAccountHistory($currentType, $accountId);

        $this->updateControl->addRenderView(
                'memberPointHistoryList', 'memberPoint_history_manager', array(
            'memberPointHistoryList' => $mpList,
            'memberPointTypeId' => $currentType->getId()
        ));
    }

}
